package tech.xs.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.xs.auth.api.domain.bo.path.EditAuthPathRoleBo;
import tech.xs.auth.domain.entity.AuthPathRole;
import tech.xs.auth.domain.exception.AuthException;
import tech.xs.auth.service.AuthPathRoleService;
import tech.xs.auth.service.AuthPathService;
import tech.xs.common.framework.domain.enums.DataSourceTypeEnum;
import tech.xs.common.framework.domain.model.ApiResult;

import javax.annotation.Resource;

@Slf4j
@Validated
@RestController
@RequestMapping("/path/role")
public class AuthPathRoleController {

    @Resource
    private AuthPathRoleService authPathRoleService;
    @Resource
    private AuthPathService authPathService;

    @GetMapping("/isUsedRoleCode")
    public ApiResult<Boolean> isPathAuth(@RequestParam String roleCode) {
        if (StrUtil.isBlank(roleCode)) {
            throw new AuthException("roleCode 不能为空");
        }
        long count = authPathRoleService.count(Wrappers.<AuthPathRole>lambdaQuery().eq(AuthPathRole::getRoleCode, roleCode));
        if (count >= 0) {
            log.info("角色已经被使用 角色已经绑定路径 roleCode:" + roleCode);
            return ApiResult.success(true);
        } else {
            return ApiResult.success(false);
        }
    }

    @PostMapping("/update/byRoleCode")
    public ApiResult<Void> updateByRoleCode(@RequestBody EditAuthPathRoleBo bo) {
        authPathRoleService.update(Wrappers.<AuthPathRole>lambdaUpdate()
                .set(bo.getStatus() != null, AuthPathRole::getStatus, bo.getStatus())
                .ne(AuthPathRole::getSource, DataSourceTypeEnum.SystemGeneration)
                .eq(AuthPathRole::getRoleCode, bo.getRoleCode()));
        authPathService.reloadAllAuthPathCache();
        return ApiResult.success();
    }

}
